using MediatR;
using SmartApplication.Api.Applient.Command.Source;
using SmartApplication.ApiCode;
using SmartApplication.Domain.Entity;
using SmartApplication.Infrastructure.Instrument;

namespace SmartApplication.Api.Applient.CommandHandler.Source
{
    public class BatchDeleteSourceHandler : IRequestHandler<BatchDeleteSourceCommand, ApiResult<int>>
    {
        public BatchDeleteSourceHandler(IBaseRepository<SourceModel> sourceRepository)
        {
            SourceRepository = sourceRepository;
        }

        public IBaseRepository<SourceModel> SourceRepository { get; }

        /// <summary>
        /// 批量逻辑删除溯源信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ApiResult<int>> Handle(BatchDeleteSourceCommand request, CancellationToken cancellationToken)
        {
            var res = new ApiResult<int>();

            int successCount = 0;
            
            foreach (var id in request.Ids)
            {
                var source = await SourceRepository.GetValueAsync(id);
 
                source.IsDeleted = true;
                var updateResult = await SourceRepository.UpdateAsync(source);
                if (updateResult > 0)
                {
                    successCount++;
                }
            }

            if (successCount > 0)
            {
                res.Code = EnumCode.Success;
                res.Message = $"成功删除{successCount}条数据";
                res.Data = successCount;
            }
            else
            {
                res.Code = EnumCode.Fail;
                res.Message = "批量删除失败";
                res.Data = 0;
            }

            return res;
        }
    }
}